<template>
    <div class="container">
        <Breadcrumb :items="['menu.sys', 'menu.sys.city']" />
        <a-card :title="$t('menu.sys.city')">
            <a-space fill direction="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-space fill>
                            <a-button type="primary" @click="openModal()" shape="round">
                                <template #icon><icon-plus /></template>
                                添加城市
                            </a-button>
                        </a-space>
                    </a-col>
                    <a-col :flex="1">
                        <a-space align="end" style="justify-content: flex-end;" fill>
                            <a-button shape="circle" @click="fetchData">
                                <template #icon><icon-refresh /></template>
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

                <a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
                    @page-change="onPageChange" @page-size-change="onPageSizeChange">
                    <template #columns>
                        <a-table-column title="ID" data-index="id" :width="80" />
                        <a-table-column title="城市名称" data-index="name" />
                        <a-table-column title="城市代码" data-index="code" :width="120" />
                        <a-table-column title="图片" data-index="image" :width="80">
							<template #cell="{ record }">
								<a-image :src="record.image_url" width="40" height="40" />
							</template>
						</a-table-column>
                        <a-table-column title="状态" data-index="status" :width="100">
                            <template #cell="{ record }">
                                <a-tag :color="record.status === 1 ? 'green' : 'red'">
                                    {{ record.status === 1 ? '启用' : '禁用' }}
                                </a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column title="创建时间" data-index="created_at" :width="180">
                            <template #cell="{ record }">
                                {{ formatTime(record.created_at) }}
                            </template>
                        </a-table-column>
                        <a-table-column title="更新时间" data-index="updated_at" :width="180">
                            <template #cell="{ record }">
                                {{ formatTime(record.updated_at) }}
                            </template>
                        </a-table-column>
                        <a-table-column title="操作" align="center" :width="120">
                            <template #cell="{ record }">
                                <a-space size="mini">
                                    <a-link @click="openModal(record)">
                                        编辑
                                    </a-link>
                                    <a-popconfirm position="left" content="确定要删除这个城市吗？" @ok="handleDelete(record.id)">
                                        <a-link>
                                            删除
                                        </a-link>
                                    </a-popconfirm>
                                </a-space>
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </a-space>
        </a-card>

        <a-modal v-model:visible="modalVisible" :title="formData.id ? '编辑城市' : '添加城市'" @before-ok="handleSubmit"
            @cancel="closeModal">
            <a-form :model="formData" ref="formRef" layout="vertical">
                <a-form-item field="name" label="城市名称" :rules="[{ required: true, message: '请输入城市名称' }]">
                    <a-input v-model="formData.name" placeholder="请输入城市名称" />
                </a-form-item>
                <a-form-item field="code" label="城市代码" :rules="[{ required: true, message: '请输入城市代码' }]">
                    <a-input v-model="formData.code" placeholder="请输入城市代码" />
                </a-form-item>
                <a-form-item label="图片" :rules="[{ required: true }]">
                    <a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload" :limit="1"
                        :file-list="fileList" image-preview @before-remove="beforeRemove" />
                    <template #extra>
                        <div>请保持图片比例为1:1，格式为jpg/png</div>
                    </template>
                </a-form-item>
                <a-form-item field="status" label="状态">
                    <a-radio-group v-model="formData.status">
                        <a-radio :value="1">启用</a-radio>
                        <a-radio :value="0">禁用</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption, FileItem } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryCityList, submitCityForm, delCity, CityRecord, CityModel } from '@/api/city';
import { uploadFile } from '@/api/upload';

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const formRef = ref();
const fileList = ref<{ url: string }[]>([]);

const basePagination = {
    current: 1,
    pageSize: 10,
    total: 0,
};

const pagination = reactive({
    ...basePagination,
});

const generateFormData = () => {
    return {
        id: 0,
        name: '',
        code: '',
        status: 1,
        image: '',
    };
};

const formData = ref(generateFormData());

const renderData = ref<CityRecord[]>([]);

const fetchData = async () => {
    setLoading(true);
    try {
        const { data } = await queryCityList({
            page: pagination.current,
            pageSize: pagination.pageSize,
        });
        renderData.value = data.list;
        pagination.total = data.total;
    } catch (err) {
        Message.error('获取城市列表失败');
    } finally {
        setLoading(false);
    }
};

const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
};

const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
};

const openModal = (record?: CityRecord) => {
    if (record) {
        formData.value = {
            id: record.id,
            name: record.name,
            code: record.code,
            status: record.status,
            image: record.image,
        };
    } else {
        formData.value = generateFormData();
    }
    modalVisible.value = true;
};

const closeModal = () => {
    modalVisible.value = false;
    formData.value = generateFormData();
};


const handleUpload = (option: any): UploadRequest => {
	try {
		const { onProgress, onError, onSuccess, fileItem } = option;

		const uploadFormData = new FormData();
		uploadFormData.append('file', fileItem.file);
		
		uploadFile(uploadFormData).then(({ data }) => {
			formData.value.image = data.path;
			fileList.value = [{ url: data.url } as FileItem];
			Message.success('上传成功');
		}).catch((err) => {
			Message.error('上传失败');
		});

		return {
			abort: () => { },
		};
	} catch (err) {
		Message.error('上传失败');
		return {
			abort: () => { },
		};
	}
};

const beforeRemove = async (fileItem: FileItem): Promise<boolean> => {
	formData.value.image = '';
	fileList.value = [];
	return true;
};

const handleSubmit = async (done: any) => {
    setLoading(true);
    try {
        await submitCityForm(formData.value).then((res) => {
            Message.success(res.msg || '操作成功');
            closeModal();
            fetchData();
            done(true);
        });
    } catch (err) {
        done(false);
    } finally {
        setLoading(false);
    }
};

const handleDelete = async (id: number) => {
    try {
        await delCity(id);
        Message.success('删除成功');
        fetchData();
    } catch (err) {
        Message.error('删除失败');
    }
};

const formatTime = (timestamp: number) => {
    if (!timestamp) return '-';
    const date = new Date(timestamp * 1000);
    return date.toLocaleString('zh-CN');
};

onMounted(() => {
    fetchData();
});
</script>

<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;
}
</style>

<script lang="ts">
export default {
    name: 'SysCity',
};
</script>
